<?php
/**
 * Created by 无所谓已
 * User: Administrator
 * Date: 2025-09-01
 * Time: 22:21
 */
namespace app\service;

class StableWorkerIdService
{
    private static $uniqueId = null;

    public static function getStableWorkerId()
    {
        if (self::$uniqueId !== null) {
            return self::$uniqueId;
        }

        $storagePath = runtime_path() . '/stable_worker_id.dat';

        // 检查是否存在已存储的ID
        if (file_exists($storagePath)) {
            self::$uniqueId = trim(file_get_contents($storagePath));
            return self::$uniqueId;
        }

        // 生成基于机器特征的稳定ID
        self::$uniqueId = self::generateStableId();

        // 保存到文件
        file_put_contents($storagePath, self::$uniqueId);

        return self::$uniqueId;
    }

    private static function generateStableId()
    {
        // 获取机器MAC地址
        $macAddress = self::getMacAddress();

        // 获取机器名和其他稳定特征
        $machineData = [
            'mac' => $macAddress,
            'hostname' => gethostname(),
            'system' => php_uname('s') . php_uname('n') . php_uname('m')
        ];

        return hash('sha256', json_encode($machineData));
    }

    private static function getMacAddress()
    {
        $mac = '';

        // 尝试获取MAC地址
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            // Windows系统
            $mac = shell_exec('getmac');
        } else {
            // Unix/Linux系统
            $mac = shell_exec('cat /sys/class/net/*/address | head -n 1');
        }

        // 如果无法获取真实MAC，则使用替代方案
        if (empty($mac)) {
            $mac = php_uname() . gethostname();
        }

        return trim($mac);
    }
}